package com.animee.jiujiangdict;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

import com.animee.jiujiangdict.db.DBManager;

import java.util.ArrayList;
import java.util.List;

public class SearchChengyuActivity extends AppCompatActivity {
    EditText cyEt;
    GridView cyGv;
    List<String>mDatas;
    ArrayAdapter<String> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_chengyu);
        cyEt = findViewById(R.id.searchcy_et);
        cyGv = findViewById(R.id.searchcy_gv);
        mDatas = new ArrayList<>();
     //创建适配器对象
        adapter = new ArrayAdapter<>(this, R.layout.item_searchcy_gv,
                R.id.item_searchcy_tv, mDatas);
        cyGv.setAdapter(adapter);
        //设置GridView每一项的点击事件
        setGvListener();
    }
    /* 设置GridView每一项点击事件的方法*/
    private void setGvListener() {
        cyGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String msg = mDatas.get(position);
                Intent intent = new Intent(SearchChengyuActivity.this,
                        ChengyuInfoActivity.class);
                intent.putExtra("chengyu",msg);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initDatas();
        cyEt.setText("");
    }

    /* 初始化GridView数据的方法*/
    private void initDatas() {
        mDatas.clear();
        try{
            List<String> list = DBManager.queryAllCyFromCyutb();
            mDatas.addAll(list);
            adapter.notifyDataSetChanged();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.searchcy_iv_back:
                finish();
                break;
            case R.id.searchcy_iv_sh:
                String text = cyEt.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    return;
                }
                if (text.length()!=4){
                    Toast.makeText(this,"当前版本只能搜索四字成语！",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(this, ChengyuInfoActivity.class);
                intent.putExtra("chengyu",text);  //将值传递到ChengyuInfoActivity当中
                startActivity(intent);
                break;
        }
    }
}
